package server

import (
	"context"
	"errors"
	"fmt"
	"math/rand"
	"time"
	"zg4zk2/common/initialize"
	"zg4zk2/common/models"
	"zg4zk2/common/proto/user"
	"zg4zk2/common/token"
)

func SendSms(in *user.SendSmsReq) (*user.SendSmsResp, error) {
	code := rand.Intn(9000) + 1000
	if len(in.Mobile) != 11 {
		return nil, errors.New("手机号格式不对")
	}
	//sms, err := pkg.SendSms(in.Mobile, strconv.Itoa(code))
	//if err != nil {
	//	return nil, errors.New("发送失败")
	//}
	//if *sms.Body.Code != "OK" {
	//	return nil, errors.New(*sms.Body.Message)
	//}
	initialize.Rdb.Set(context.Background(), "sendSms"+in.Source+in.Mobile, code, time.Minute*3)
	incr := initialize.Rdb.Incr(context.Background(), "sendSmsIncr"+in.Mobile)
	if incr.Val() >= 3 {
		initialize.Rdb.Expire(context.Background(), "sendSmsIncr"+in.Mobile, time.Hour*1)
		return nil, errors.New("发送验证码超过三次，请一个小时后再尝试")
	}
	return &user.SendSmsResp{}, nil
}

func Login(in *user.LoginReq) (*user.LoginResp, error) {
	var users *models.User
	get := initialize.Rdb.Get(context.Background(), "sendSmsLogin"+in.Mobile)
	if get.Val() != in.Code {
		return nil, errors.New("验证码错误")
	}
	err := initialize.DB.Where("mobile=?", in.Mobile).Find(&users).Error
	if err != nil {
		return nil, errors.New("查询失败")
	}
	if users.ID == 0 {
		fmt.Println("该用户没有注册,已自动注册")
		users = &models.User{
			Mobile:   in.Mobile,
			Password: in.Password,
		}
		err = initialize.DB.Create(&users).Error
		if err != nil {
			return nil, errors.New("创建失败")
		}
	}
	if users.Password != in.Password {
		return nil, errors.New("密码错误")
	}
	claims := token.CustomClaims{ID: users.ID}
	createToken, err := token.NewJWT("2209a").CreateToken(claims)
	if err != nil {
		return nil, errors.New("token生成失败")
	}
	return &user.LoginResp{Greet: createToken}, nil
}
